#!/usr/bin/env bash
#   自动部署普通web项目
#   param1 string  http://...../xxx.war
#   param2 string  http://..../tomcat.tar.gz
#   param3 string  /xxxx/xxxx/tomcat
#   param4 string  /xxxx/xxxx/tomcat
#   @description 
#   @author konbluesky 
#   @date 2017-04-18 11:03:45

#war包下载地址
WAR_URL=$1
#容器url
CONTAINER_URL=$2
#安装目录
#WORK_DIR=/usr/local/lib/ambari-service
WORK_DIR=$3
#容器端口
CONTAINER_PORT=$4

echo "check params"
check_param () {
    if [ ! $3 ]; then  
        WORK_DIR=/usr/local/lib/ambari-service 
    fi
}
check_param
echo "WORK_DIR:${WORK_DIR}"
#下载前置删除操作
pre_download () {
    rm -rf /tmp/tomcat.tar.gz
    rm -rf /tmp/webapp.war
    rm -rf ${WORK_DIR}
    tomcatpid=`lsof -i :$CONTAINER_PORT|grep -v "PID" | awk '{print $2}'`
    echo "tomcatpid:${tomcatpid}"
    #启动前 check 
    if [ "${tomcatpid}" != "" ]; then
        echo "tomcat is started,PID:${tomcatpid} now stop it"
        kill -9 "${tomcatpid}" >/dev/null 2>&1  
    fi
}

echo "download before cleanning..."
pre_download
echo "clean over."

wget -O /tmp/tomcat.tar.gz $CONTAINER_URL
#cp /tmp/tomcat.tar.gz $CONTAINER_URL
mkdir -p $WORK_DIR
tar -zxf /tmp/tomcat.tar.gz -C $WORK_DIR 
#hack write
#cd apache-tomcat-8.5.13
rm -rf $WORK_DIR/apache-tomcat-8.5.13/webapps/*
wget -O /tmp/webapp.war $WAR_URL


if [ -d "${WORK_DIR}/apache-tomcat-8.5.13" ]; then
    echo "apache tomcat  installed ,cp war file to tomcat. port:${CONTAINER_PORT}"
    cp /tmp/webapp.war $WORK_DIR/apache-tomcat-8.5.13/webapps/ROOT.war
    sed -i 's/Connector port="8080"/Connector port="'${CONTAINER_PORT}'"/g' $WORK_DIR/apache-tomcat-8.5.13/conf/server.xml
    sh $WORK_DIR/apache-tomcat-8.5.13/bin/startup.sh
else
    echo "${WORK_DIR}/apache-tomcat-8.5.13 not found , please check!"
fi


